<?php

class Model_Listing_Motorcycle extends Model_Listing implements Model_Listing_Interface
{
    const MILEAGE_MIN = 0;
    const MILEAGE_MAX = 2000000;

    protected static  $_collection = 'listing';


    protected static $_requirements = array(
     //   'em'  => array('Required', 'Validator:EmailAddress'), //Email
        'exc'  => array('Array'), //exteriorcolor   
    );

    protected $_category = array();

    public function __construct($data = array(), $config = array()) {
        static::$_transcript = array_merge(array(
            'ma' => 'make',
            'mo' => 'model',
            'mt' => 'motorcycletype',
            'ym' => 'yearmanufactured',
            'npo' => 'numberpreviousowner',
            'mil' => 'mileage',
            'em' => 'enginemotor',
            'tr' => 'transmission',
            'exc' => 'exteriorcolor',
            'sb' => 'saleby',
            'arl1'  => 'area_l1',
            'arl2'  => 'area_l2',
            'dsp'  => 'displacement',
            'brs'  => 'brandsale',
         ), static::$_transcript);
        parent::__construct($data, $config);
    }


    public function __get($name)
    {
        if ($name == 'model') {
            return  Model_Listing_Attribute::one(array('_id' => new MongoId($this->mo)));
        } elseif ($name == 'make') {
            return  Model_Listing_Attribute::one(array('_id' => new MongoId($this->ma)));
        } else {
            return parent::__get($name);
        }
    }

	public static function getTranslationFormField()
    {
        $arr = array(
			'tl_en' =>'text',
			'cs_en' =>'textarea',
		);
		
		return $arr;
    }
    public function postAnAddForm($options = array()) {
        $options = array_merge($options, array('category' => $this->category));
        return new Listing_Form_PostAnAddMotorcycleForm($options);
    }

    public function getAdDetailPartialName()
    {
        return 'customization/motorcycle.phtml';
    }

    public function getAdPreviewPartialName()
    {
        return $this->getAdDetailPartialName();
    }


    public static function getSearchResultPartialName()
    {
        return 'motorcycles';
    }
    public static function getRefineSearchForm()
    {
        return new Search_Form_MotorcycleRefineForm();
    }

    public static function processRefineSearchForm(&$get, $page, $per_page, &$query, &$fields, &$additionalParameters)
    {
        //echo '<pre>';print_r($_GET);exit;

        //$q       = isset($_GET['keyword']) ? strtolower($_GET['keyword']) : false;
        $results = false;
        if(empty($fields)) {
            $fields  = array('description', 'title', 'area_l2_name', 'area_l1_name', 'street');
        }
        if(empty($additionalParameters)) {
            $additionalParameters = array();
        }
        $values  = array();

        //$get     = $_GET;

        $search_terms = self::getSearchTextTerms();
        
        $exact_search_terms = self::getExactSeachTerms();
        
        $q      = '';
        $qq     = !empty($_GET['keyword']) ? $_GET['keyword'] : '';
        $to_add = ' ';

        //add the username
        if (!empty($get['keyword'])) {
            //$q = '(username_lower:"'.$get['keyword'].'"^50.0) ';
        }

        if (!empty($exact_search_terms)) {
            foreach($exact_search_terms as $name => $val) {
                foreach($val as $k => $v) {
                    if (preg_match('#('.trim($v).')#i', $get['keyword'], $match)) {
                        //var_dump($match, $v, $get['keyword'], str_ireplace( $v, '', $get['keyword']));
                        $get['keyword'] = str_ireplace( $v, '', $get['keyword']);
                        $q .= $to_add.str_replace('_name', '', $name) .':'.$k.'^5.0 ';
                        $to_add = ' OR ';
                    }
                }
            }
            if (!empty($q) && !empty($tmp)) {
                $q = ' OR ('.$tmp.') ';
            }
        }
        
        $pattern = '#(?<=([0-9]))\s+bedroom[s]?#iu';
        if (preg_match($pattern, strtolower($get['keyword']), $match)) {
            $qq = str_ireplace($match[1].$match[0], '"'.$match[1].$match[0].'"', $qq);
            $get['keyword'] = str_ireplace($match[1].$match[0], '', $get['keyword']);
            $tmp = ' bedroom:'.trim($match[1]).'^9.0 ';
            if (!empty($q)) {
                $q .= ' OR ('.$tmp.') ';
            } else {
                $q = $tmp;
            }
        }
        
        $to_add = ' ';
        
        //remove quoted words and add them to q
        $bak = $get['keyword'];
        
        
        $arr = preg_match_all('#\"(.*?)\"#i', $get['keyword'], $match);
        foreach ($match[1] as $v) {
            $q .= ' AND "'.$v.'"';
        }
        $get['keyword'] = preg_replace('#"(.*?)"#i', '', $get['keyword']);
        $qf = '';
        foreach($search_terms as $v => $weight) {
            $qf .= $v.'^'.$weight.' ';
        }
        
        if (!empty($qf)) {
            $additionalParameters['qf'] = $qf;
        }
        if (!empty($qq)) {
            $additionalParameters['qq']   = $qq;
        }  
        
        $get['keyword'] = trim($get['keyword']);
        if (!empty($get['keyword'])) {
            if (!empty($q)) {
                $q.=' OR ';
            }
            $q .='(';
            foreach ($fields as $f) {
                $list = explode(' ', trim($get['keyword']));
                foreach($list as $vl) {
                    if (!empty($vl)) {
                        $q .= $to_add.''.$f.':'.$vl;
                        $to_add = ' OR ';
                    }
                }
            }
            $q.=') ';
        }
        
        
        $q.= ' OR _query_:"{!dismax qf=$qf v=$qq}" ';
        
        if (empty($_GET['keyword'])) {
            $q = '*:*';
        }
        
        $query = $q;
        $get['sort'] = empty($get['sort']) ? '' : $get['sort'];
        

        switch ($get['sort']) {
            case 'highest':
                $get['sort'] = 'highest';
                $sort = 'price desc';
                break;
            case 'lowest':
                $get['sort'] = 'lowest';
                $sort = 'is_free asc, price asc';
                break;
            case 'rel':
                $get['sort'] = 'rel';
                $sort = 'score desc';
                break;
            case 'recent':
                $get['sort'] = 'recent';
                $sort = 'posted_at desc';
                break;
            case 'status':
                $get['sort'] = 'status';
                $sort = 'status desc';
                break;
            default:
                if (!empty($get['keyword_motorcycle'])) {
                    $get['sort'] = 'rel';
                    $sort         = 'score desc';
                } else {
                    $get['sort'] = 'recent';
                    $sort         = 'posted_at desc';
                }
        }

        $additionalParameters['fl']   = '*,score';
        $additionalParameters['sort'] = $sort;


        //Parameters to refine search
        $fq         = '';
        if(!empty($additionalParameters['fq'])) {
            $fq = $additionalParameters['fq'];
        }
        $valuesplus = array();

        //Has Image
        if (!empty($get['has_image'])) {
            $valuesplus['has_image'] = true;
        }
        //Preferred Seller
        if (!empty($get['agency_owner_motorcycle'])) {
            $valuesplus['saleby'] = $get['agency_owner_motorcycle'];
        }
        elseif (!empty($get['seller']['saleby'])) {
            $valuesplus['saleby'] = $get['seller']['saleby'];
        }

        // Sale by
        if (!empty($get['wantto_motorcycle'])) {
            $buy_rent = $get['wantto_motorcycle'];
        }
        elseif (!empty($get['want_to']['buy_rent'])) {
            $buy_rent = $get['want_to']['buy_rent'];
        }

        // Sale by
        if (!empty($buy_rent)) {
            if ($buy_rent == 'Buy') {
                //Sale Category
                $sales = array();
                $sale = Model_Category::one(array('id' => 'c582'));
                $sales1 = $sale->_id;
                $sale = Model_Category::one(array('id' => 'c581'));
                $sales2 = $sale->_id;
                $category = ' +(category:'.$sales1.' OR category:'.$sales2.') ';
            }
            elseif ($buy_rent == 'Rent') {
                $rents = array();
                $rent = Model_Category::one(array('id' => 'c583'));
                $rents1 = $rent->_id;
                $category = ' +category:'.$rents1;
            }
            else {
                $category =' ';
            }
        }

        //Force only Motorcycles
        //$valuesplus['type_obj_s'] = 'Model_Listing_Motorcycle';
        if(strpos($fq, '+type_obj_s') === false) {
            $valuesplus['type_obj_s'] = 'Model_Listing';
        }

        //Make
        if (!empty($get['performances']['make'])) {
            $valuesplus['make'] = $get['performances']['make'];
        }
        if (!empty($get['make_motorcycle'])) {
            $valuesplus['make'] = $get['make_motorcycle'];
        }

        //Model
        if (!empty($get['performances']['model'])) {
            $valuesplus['model'] = $get['performances']['model'];
        }
        if (!empty($get['model_motorcycle'])) {
            $valuesplus['model'] = $get['model_motorcycle'];
        }

        //Motorcycle Type
        if (!empty($get['performances']['motorcycletype'])) {
            $valuesplus['motorcycletype'] = $get['performances']['motorcycletype'];
        }
        if (!empty($get['motorcycletype'])) {
            $valuesplus['motorcycletype'] = $get['motorcycletype'];
        }

        //Price
        //var_dump($get);exit;
        if (isset($get['performances-price']) && isset($get['performances-price-1'])) {
            $price  = $get['performances-price'];
            $price1 = $get['performances-price-1'];
        }
        elseif (isset($get['price_motorcycle']) && isset($get['price_motorcycle-1'])) {
            $price  = $get['price_motorcycle'];
            $price1 = $get['price_motorcycle-1'];
        }
        if (isset($price) && isset($price1)) {
            $test1 = false;$test2 = false;
            if (empty($price1)) {
                $price1 = '*';
                $test1 = true;
            }
            if (empty($price)) {
                $price = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['price'] = '['.intval(str_replace(",","",$price)).' TO '.intval(str_replace(",","",$price1)).']';
            }
        }

        //Year Manufactured
        if (!empty($get['performances']['yearmanufactured'])) {
            $valuesplus['yearmanufactured'] = $get['performances']['yearmanufactured'];
        }
        if (!empty($get['yearmanufactured_motorcycle'])) {
            $valuesplus['yearmanufactured'] = $get['yearmanufactured_motorcycle'];
        }

        //No of previous Owners
        if (!empty($get['performances']['previousowners'])) {
            $valuesplus['nopreviousowners'] = $get['performances']['previousowners'];
        }

        //Mileage
        if (isset($get['performances-mileage']) && isset($get['performances-mileage-1'])) {
            $test1 = false;$test2 = false;
            if ($get['performances-mileage-1'] == Model_Listing_Motorcycle::MILEAGE_MAX) {
                $get['performances-mileage-1'] = '*';
                $test1 = true;
            }
            if ($get['performances-mileage'] == Model_Listing_Motorcycle::MILEAGE_MIN) {
                $get['performances-mileage'] = '0';
                $test2 = true;
            }
            if (!$test1 || !$test2) {
                $valuesplus['mileage'] = '['.$get['performances-mileage'].' TO '.$get['performances-mileage-1'].']';
            }
        }

        //Engine Motor
        if (!empty($get['optional']['enginemotor'])) {
            $valuesplus['enginemotor'] = $get['optional']['enginemotor'];
        }

        //Transmission
        if (!empty($get['optional']['transmission'])) {
            $valuesplus['transmission'] = $get['optional']['transmission'];
        }

        //Exterior Color
        if (!empty($get['optional']['exteriorcolor'])) {
            $valuesplus['exteriorcolor'] = $get['optional']['exteriorcolor'];
        }

        // District
        if (!empty($get['area_l2'])) {
            $valuesplus['area_l2'] = $get['area_l2'];
        }
        elseif (!empty($get['performances']['area_l2'])) {
            $valuesplus['area_l2'] = $get['performances']['area_l2'];
        }

        if (!empty($get['city'])) {
            $valuesplus['city'] = (int) $_GET['city'];
        }

        foreach($valuesplus as $k => $val) {
          $valuesplus[$k] = '+'.$k.':'.$val.' ';
        }

        if (!empty($category)) {
            $fq .= $category;
        }

        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }
       
    }

    public static function findMake($name)
    {
        $lang = Zend_Registry::get('current_language');
        $view = Zend_Registry::get('Zend_View');
        $key = 'nm_'.$lang;
        $attr      = Model_Listing_Attribute::one(array('type' => 'motorcycles', $key  => $name));
        if (!empty($attr)) {
            return $attr->_id;
        }
    }

    public static function findModel($name, $make)
    {
        $lang = Zend_Registry::get('current_language');
        $view = Zend_Registry::get('Zend_View');
        $make = array();
        $key = 'nm_'.$lang;
        $attr      = Model_Listing_Attribute::all(array('type' => 'motorcycles', 'path' => new MongoId($make), $key  => $name))->sort(array('or' => 1, 'nm_en' => 1));
        foreach($attr as $k => $loc) {
            $make[(string) $loc->_id] = $loc->name;
        }

        return $make;

    }

    public static function getMake()
    {
        $view = Zend_Registry::get('Zend_View');
        $make = array();
        $attr      = Model_Listing_Attribute::all(array('type' => 'motorcycles', 'path' => array('$exists' => 0)))->sort(array('order' => 1, 'name' => 1));
        $make[''] = 'All';

        foreach($attr as $k => $loc) {
            $make[(string) $loc->_id] = $loc->name;
        }

        return $make;
    }

    public static function getMakePostAd()
    {
        $view = Zend_Registry::get('Zend_View');
        $make = array();
        $attr      = Model_Listing_Attribute::all(array('type' => 'motorcycles', 'path' => array('$exists' => 0), 'cn' => array('$exists' => true)))->sort(array('order' => 1, 'name' => 1));
        $make[''] = 'Select';

        foreach($attr as $k => $loc) {
            $make[(string) $loc->_id] = $loc->nm_sc;
        }

        return $make;
    }

    public static function getModel($id)
    {
        $view = Zend_Registry::get('Zend_View');
        $model = array();
        $attr = Model_Listing_Attribute::all(array('path' => new MongoId($id)))->sort(array('order' => 1, 'name' => 1));
        $model[''] = 'All';

        foreach($attr as $k => $loc) {
            $model[(string) $loc->_id] = $loc->name;
        }
        //exit;
        return $model;
    }

    public static function getModelPostAd($id)
    {
        $view = Zend_Registry::get('Zend_View');
        $model = array();
        $attr = Model_Listing_Attribute::all(array('path' => new MongoId($id)))->sort(array('order' => 1, 'name' => 1));
        $model[''] = 'Select';

        foreach($attr as $k => $loc) {
            $model[(string) $loc->_id] = $loc->name;
        }
        //exit;
        return $model;
    }

    public static function getYearManufactured($id = null)
    {
      $res = array(
            '' => 'Select',
            2010 => 2012,
            2010 => 2011,
			2010 => 2010,
            2009 => 2009,
            2008 => 2008,
            2007 => 2007,
            2006 => 2006,
            2005 => 2005,
            2004 => 2004,
            2003 => 2003,
            2002 => 2002,
            2001 => 2001,
            2000 => 2000,
            1999 => 1999,
            1998 => 1998,
            1997 => 1997,
            1997 => 1996,
            1997 => 1997,
            1996 => 1996,
            1995 => 1995,
            1994 => 1994,
            1993 => 1993,
            1992 => 1992,
            1991 => 1991,
            1990 => 1990,
            1989 => 1989,
            1988 => 1988,
            1987 => 1987,
            1986 => 1986,
            1985 => 1985,
            1984 => 1984,
            1983 => 1983,
            1982 => 1982,
            1981 => 1981,
            1980 => 1980,
            1979 => 1979,
            1978 => 1978,
            1977 => 1977,
            1976 => 1976,
            1975 => 1975,
            1974 => 1974,
            1973 => 1973,
            1972 => 1972,
            1971 => 1971,
            1970 => 1970,
        );
      
        if ($id !== null) {
            return $res[$id];
        }
        return $res;       
    }

    public static function getPreviousOwners($id = null)
    {
        $res = array(
            '' => 'All',
            1 => '1',
            2 => '2',
            3 => '3',
            4 => '4+',
        );
      
        if ($id !== null) {
            return $res[$id];
        }
        return $res;         
    }

    public static function getEngineMotor($id = null)
    {
        $res = array('' => 'All') + self::getEngineMotorPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        
        return $res;   
    }
    
    public static function getEngineMotorPostAd()
    {
        return array(
            1 => '250 cc or below',
            2 => '251 -600 cc',
            3 => '601-750 cc',
            4 => '751 - 900 cc',
            5 => '901 - 1300 cc',
            6 => '1301 -1500 cc',
            7 => '+1500 cc'
        );
    }


    public static function getTransmission($id = null)
    {
        $res = array('' => 'All') + self::getTransmissionPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        
        return $res;  
    }

    public static function getTransmissionPostAd()
    {
        return array(
            1 => 'Automatic',
            2 => 'CVT',
            3 => 'Manual',
            4 => 'Semi-automatic',
            5 => 'Other'
        );
    }

    public static function getExtColor($id = null)
    {
        $res = array('' => 'All') + self::getExtColorPostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        
        return $res;  
    }

    public static function getExtColorPostAd()
    {
        return array(
        	''=> 'Select',
            1 => '黑色',
            2 => '白色',
            3 => '红色',
            4 => '蓝色',
            5 => '绿色',
            6 => '黄色',
            7 => '橘色',
            8 => '香槟色',
            9 => '多颜色',
            10 => '咖啡色',
            11 => '银灰色',
            12 => '深灰色',
            13 => '金色',
            14 => '紫色',
            15 => '棕色',
            16 => '其他'
        );
    }

    public static function getMotorcycleType($id = null)
    {
        $res = array('' => 'All') + self::getMotorcycleTypePostAd();
        
        if ($id !== null) {
            return $res[$id];
        }
        
        return $res;  
    }

    public static function getMotorcycleTypePostAd()
    {
        return array(
            '' => 'Select',
            1 => '弯梁车',
            2 => '踏板车',
            3 => '骑式车',
            4 => '太子车',
            5 => '迷你车',
            6 => '越野摩托',
            7 => '沙滩车',
            8 => '大排量',
            9 => '公路赛车',
            10 => '三轮摩托',
        );
    }

    public static function getMileagePostAd($id = null)
    {
        $res = array(
            '5000' => '5000',
            '10000' => '10000',
            '20000' => '20000',
            '30000' => '30000',
            '40000' => '40000',
            '50000' => '50000',
            '60000' => '60000',
            '70000' => '70000',
            '80000' => '80000',
            '90000' => '90000',
            '100000' => '100000',
            '110000' => '110000',
            '120000' => '120000',
            '130000' => '130000',
            '140000' => '140000',
            '150000' => '150000',
            '160000' => '160000',
            '170000' => '170000',
            '180000' => '180000',
            '190000' => '190000',
            '[200000 TO *]' => '200000 +'
        );
        
        if ($id !== null) {
            return $res[$id];
        }
        
        return $res;          
    }   
    

    public static function getSearchTextTerms() 
    {
        return array(
            'description' => '1.0', 
            'title' => '7.0', 
            'make_name' => '9.0', 
            'model_name' => '9.0',
            'area_l2_name' => '9.0',
            'street' => '7.0',
            'exteriorcolor_name' => '5.0',
        );
    }
    
    
    /*
     * return a list of all the possible values that should be extracted from the keyword search and be specified as exact term
     * 
     */
    public static function getExactSeachTerms() 
    {
       return array(
                'motorcycletype_name'        => self::getMotorcycleType(),
                'exteriorcolor_name'         => self::getExtColor(),
                'yearmanufactured'           => self::getYearManufactured(),
           );
    }               

    public function getSolrDocument($document = null)
    {
        if (!$document instanceof Apache_Solr_Document) {
            $document = new Apache_Solr_Document();
        }
        $view = Zend_Registry::get('Zend_View');
        
        if(!empty($this->ma)) {
            if (!empty($this->make->name)) {
                $document->make          = (string)$this->ma;
                $document->make_name             = (string)$this->make->name;
            }
        }
        $document->model         = (string)$this->mo;
        if(!empty($this->mo)) {
            if (!empty($this->model->name)) {
                $document->model_name            = (string)$this->model->name;
                if (is_array($this->model->tags)) {
                    foreach($this->model->tags as $tags) {
                        $document->addField('model_name', (string)$tags);
                    }
                }
            }
        }
        if (!empty($this->ym)) {
            $document->yearmanufactured = (int)$this->ym;
        }
        if ($this->npo === 0 || !empty($this->npo)) {
            $document->nopreviousowners = (int)$this->npo;
        }
        if (!empty($this->et)) {
            $document->enginetype       = (int)$this->et;
        }
        if (!empty($this->dit)) {
            $document->drivetype        = (string)$this->dit;
            $document->addField('drivetype_name', self::getDriveType($this->dit));
            $document->addField('drivetype_name', $view->t(self::getDriveType($this->dit), Model_Translate::TC));
        }
        if (!empty($this->sb)) {
            $document->saleby           = (string)$this->sb;
        }
        if (!empty($this->dn)) {
            $document->dealername       = (string)$this->dn;
        }
        //$document->dealerphone      = (int)$this->dp;
        //$document->dealeremail      = (string)$this->de;
        if (!empty($this->mil)) {
            //$document->mileage  = (int)$this->mil;
        }
        if (!empty($this->do)) {
            $document->doors  = (int)$this->do;
        }
        if (!empty($this->ecf)) {
            foreach ((array)$this->ecf as $data) {
                $document->addField('entertainmentfeatures', (string)$data);
                $document->addField('entertainmentfeatures_name', self::getEntertComm($data));
                $document->addField('entertainmentfeatures_name',  $view->t(self::getEntertComm($data), Model_Translate::TC));
            }        
        }
        //Cars
        if (!empty($this->eng)) {
            $document->engine           = (string)$this->eng;
        }
        if (!empty($this->cap)) {
            $document->capacity         = (int)$this->cap;
        }
        
        if (!empty($this->mt)) { 
            $document->motorcycletype          = $this->mt;
            $document->addField('motorcycletype_name', self::getMotorcycleType($this->mt));
            $document->addField('motorcycletype_name', $view->t(self::getMotorcycleType($this->mt), Model_Translate::TC));
        }   
        
        if (!empty($this->hp)) {
            $document->horsepower       = (int)$this->hp;
        }
        if (!empty($this->fue)) {
            $document->fueleconomy      = (string)$this->fue;
        }
        if (!empty($this->fu)) {
            $document->fuel             = (string)$this->fu;
        }
        if (!empty($this->tr)) {
            $document->transmission_id  = (string)$this->tr;
        }

        if (!empty($this->inc)) {
            foreach ((array)$this->inc as $data) {
                $document->addField('interiorcolor', (string)$data);
                $document->addField('interiorcolor_name', self::getIntColor($data));
                $document->addField('interiorcolor_name', $view->t(self::getIntColor($data), Model_Translate::TC));
            }
        }
        if (!empty($this->exc)) {
            foreach ((array)$this->exc as $data) {
                $document->addField('exteriorcolor', (string)$data);
                $document->addField('exteriorcolor_name', self::getExtColor($data));
                $document->addField('exteriorcolor_name', $view->t(self::getExtColor($data), Model_Translate::TC));
            }
        }
        
        if (!empty($this->saf)) {
            foreach ((array)$this->saf as $data) {
                $document->addField('safetyfeatures', (string)$data);
                $document->addField('safetyfeatures_name', self::getSafetyFeatures($data));
                $document->addField('safetyfeatures_name',  $view->t(self::getSafetyFeatures($data), Model_Translate::TC));
            }
        }
        if (!empty($this->po)) {
            foreach ((array)$this->po as $data) {
                $document->addField('poweroptions', (string)$data);
                $document->addField('poweroptions_name', self::getPowerOptions($data));
                $document->addField('poweroptions_name',  $view->t(self::getPowerOptions($data), Model_Translate::TC));
            }        
        }
        return parent::getSolrDocument($document);        
    }

    public function exportRest($compressed = false)
    {
        $res = parent::exportRest($compressed);
        $view = Zend_Registry::get('Zend_View');


        $res['type'] = 'motorcycle';
        if ($compressed) {
            return $res;
        }
        
/*        
        if(!empty($this->make)) {
            $res['make'] = (string) $this->make->name;
            if(!empty($this->model)) {
                $res['model'] = (string) $this->model->name;
            }
        }
        $res['nbprevious'] = (string)$this->numberpreviousowner;
        $res['capacity'] = (string)$this->capacity;
        $res['year'] = (string)$this->yearmanufactured;
 */

        if(!empty($this->ma)) {
            if (!empty($this->make->name)) {
                $res['make']      = (string)$this->ma;
                $res['make_name'] = (string)$this->make->name;
            }
        }

        if(!empty($this->mo)) {
            $res['model'] = (string)$this->mo;        
            if (!empty($this->model->name)) {
                $res['model_name'] = (string)$this->model->name;
                if (is_array($this->model->tags)) {
                    foreach($this->model->tags as $tags) {
                        $res['model_en'] =  (string)$tags;
                    }
                }
            }
        }
        if (!empty($this->ym)) {
            $res['year'] = (string)$this->ym;
        }
        if ($this->npo === 0 || !empty($this->npo)) {
            $res['noprevious'] = (string)$this->npo;
        }
        if (!empty($this->et)) {
            $res['enginetype']       = (string)$this->et;
        }
        if (!empty($this->dit)) {
            $res['drivetype']        = (string)$this->dit;
            $res['drivetype_en'] =  self::getDriveType($this->dit);
            $res['drivetype_tc'] =  $view->t(self::getDriveType($this->dit), Model_Translate::TC);
        }
        if (!empty($this->sb)) {
            $res['saleby']           = (string)$this->sb;
        }
        if (!empty($this->dn)) {
            $res['dealername']       = (string)$this->dn;
        }

        if (!empty($this->mil)) {
            $res['mileage']  = (string)$this->mil;
        }
        if (!empty($this->do)) {
            $res['doors']  = (string)$this->do;
        }
        if (!empty($this->ecf)) {
            foreach ((array)$this->ecf as $data) {
                $res['entertainmentfeatures'] = (string)$data;
                $res['entertainmentfeatures_en'] =  self::getEntertComm($data);
                $res['entertainmentfeatures_tc'] =   $view->t(self::getEntertComm($data), Model_Translate::TC);
            }        
        }

        if (!empty($this->eng)) {
            $res['engine'] = (string)$this->eng;
        }
        if (!empty($this->cap)) {
            $res['capacity'] = (string) $this->cap;
        }
        
        if (!empty($this->mt)) { 
            $res['motorcycletype']    = $this->mt;
            $res['motorcycletype_en'] =  self::getMotorcycleType($this->mt);
            $res['motorcycletype_tc'] =  $view->t(self::getMotorcycleType($this->mt), Model_Translate::TC);
        }   
        
        if (!empty($this->hp)) {
            $res['horsepower'] = (string)$this->hp;
        }
        if (!empty($this->fue)) {
            $res['fueleconomy'] = (string)$this->fue;
        }
        if (!empty($this->fu)) {
            $res['fuel'] = (string)$this->fu;
        }
        if (!empty($this->tr)) {
            $res['transmission_id']  = (string)$this->tr;
        }

        if (!empty($this->inc)) {
            foreach ((array)$this->inc as $data) {
                $res['interiorcolor'] = (string)$data;
                $res['interiorcolor_en'] =  self::getIntColor($data);
                $res['interiorcolor_tc'] =  $view->t(self::getIntColor($data), Model_Translate::TC);
            }
        }
        if (!empty($this->exc)) {
            foreach ((array)$this->exc as $data) {
                $res['exteriorcolor'] = (string)$data;
                $res['exteriorcolor_en'] =  self::getExtColor($data);
                $res['exteriorcolor_tc'] =  $view->t(self::getExtColor($data), Model_Translate::TC);
            }
        }
        
        if (!empty($this->saf)) {
            foreach ((array)$this->saf as $data) {
                $res['safetyfeatures']    = (string)$data;
                $res['safetyfeatures_en'] =  self::getSafetyFeatures($data);
                $res['safetyfeatures_tc'] =   $view->t(self::getSafetyFeatures($data), Model_Translate::TC);
            }
        }
        if (!empty($this->po)) {
            foreach ((array)$this->po as $data) {
                $res['poweroptions']    = (string)$data;
                $res['poweroptions_en'] =  self::getPowerOptions($data);
                $res['poweroptions_tc'] =   $view->t(self::getPowerOptions($data), Model_Translate::TC);
            }        
        }        

        return $res;
    }

    public function processRestForm()
    {
        $post = $_POST;

        $make = $model = null;

        //Make
        if (empty($_POST['make'])) {
            throw new Ac_Exception_MissingInformation('Motorcycle Make is empty');
        } else {
            $tmp = new MongoId($_POST['make']);
            if (strlen($_POST['make']) == 24 && $_POST['make'] == (string) $tmp) {
                $makes = self::getMakePostAd();
                if (empty($makes[$_POST['make']])) {
                    throw new Ac_Exception_MissingInformation('Motorcycle Make is empty');
                }                
            } else {
                $make = self::findMake($_POST['make']);
                /*
                if (empty($make)) {
                    throw new Ac_Exception_MissingInformation('Motorcycle Make is empty');
                } 
                 */    
            }
        }

        if (!empty($make)) {
            $this->make = new MongoId($make);
        }

        //Motorcycle type
        $types = self::getMotorcycleTypePostAd();
        if (!empty($_POST['motorcycletype']) && $_POST['motorcycletype'] != '多彩色' &&
                empty($types[$_POST['motorcycletype']]) && array_search($_POST['motorcycletype'], $types) === false) {
            throw new Ac_Exception_MissingInformation('Motorcycle type is empty');
        }
        if (!empty($types[$_POST['motorcycletype']])) {
            $this->motorcycletype = intval($_POST['motorcycletype']);
        } elseif(($res = array_search($_POST['motorcycletype'], $types)) !== false) {
            $this->motorcycletype = intval($res);
        }        

        //Nb previous user
        $nbprevious = self::getPreviousOwners();
        if (!empty($_POST['nbprevious']) && empty($nbprevious[$_POST['nbprevious']])) {
            throw new Ac_Exception_MissingInformation('Number of previous user is empty');
        }
        if (!empty($_POST['nbprevious'])) {
            $this->numberpreviousowner = intval($_POST['nbprevious']);
        }

        //Color
        $colors = self::getExtColorPostAd();
        if (!empty($_POST['color']) && $_POST['color'] != '多彩色' &&
                empty($colors[$_POST['color']]) && array_search($_POST['color'], $colors) === false) {
            throw new Ac_Exception_MissingInformation('Color is empty');
        }
        if (!empty($colors[$_POST['color']])) {
            $this->exteriorcolor = intval($_POST['color']);
        } elseif(($res = array_search($_POST['color'], $colors)) !== false) {
            $this->exteriorcolor = intval($res);
        }


        //Year
        if (!empty($_POST['year']) && intval($_POST['year']) == 0 ) {
            throw new Ac_Exception_MissingInformation('Invalid value for year');
        }
        if (!empty($_POST['year'])) {
            $this->yearmanufactured = intval($_POST['year']);
        }

        if (!empty($_POST['displacement'])) {
            $this->displacement = $_POST['displacement'];
        }

        $price          = !empty($_POST['price']) ? $_POST['price'] : '';
        if (!empty($price) && $_POST['price'] != '' && !is_numeric($_POST['price']) ) {
            //echo 'price empty';exit;
            throw new Ac_Exception_MissingInformation('Price is not valid');
        }

        if ($price == 0 ){
            $this->price = 0;
        } elseif(empty($price)) {

        } else {
            $this->price = (float)$price;
        }

        parent::processRestForm();
        return true;
    }
}
